package com.tx.service;

import com.tx.dao.UserDao;
import com.tx.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.List;

/**
 * @author ：tx
 * @description：
 * @modified By：
 * @version:
 */
@Service("mercuryUserService")
public class MercuryUserServiceImpl implements UserDetailsService {
    @Autowired
    UserDao userDao;


    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        try {
            User user = userDao.findUserByUserName(s);
            Assert.notNull(user,"user不能为空");

            //用户权限
            List<SimpleGrantedAuthority> authorities = getAuthority(user.getRoles());
            return new org.springframework.security.core.userdetails.User(user.getUsername(),user.getPassword(),authorities);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private List<SimpleGrantedAuthority> getAuthority(String roles) {
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        String [] roleArr = roles.split(",");
        if(roleArr == null) {
            return null;
        }
        for (String role : roleArr) {
            authorities.add(new SimpleGrantedAuthority(role.trim()));
        }

        return authorities;
    }
}
